<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use Dotenv\Validator;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use App\Exception\XZXValidationException;
use App\Service\RateCustomizedService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Psr\Container\ContainerInterface;
use Hyperf\Logger\LoggerFactory;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;

/**
 * Class RateCustomizedController
 * @package App\Controller
 *
 * @Controller(prefix="/admin/api/rateCustomized")
 */
class RateCustomizedController extends AdminBaseController
{
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var RateCustomizedService
     */
    protected $RateCustomizedService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->RateCustomizedService->get($param);
    }

    /**
     * 编辑
     * @PostMapping(path = "edit")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function edit(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id'               => 'required|uuid',
                'rateGroupId'      => 'required|uuid',
                'status'           => 'required|integer|max:1|min:0',
                'sourceCurrency'   => 'required|alpha_num',                
                'targetCurrency'   => 'required|alpha_num',   
                'type'             => 'required|integer|max:4|min:1',
                'rateType'         => 'required|integer|max:5|min:1',
                'offsetType'       => 'required|integer|max:2|min:1',             
                'syncType'         => 'required|integer|max:1|min:0',      
                'offsetValue'      => 'required|integer',
                'offsetPercentage' => 'required|integer|max:100000|min:0',             
                'rate'             => 'required|integer|min:0',                 
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->RateCustomizedService->edit($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function add(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'rateGroupId'      => 'required|uuid',
                'status'           => 'required|integer|max:1|min:0',
                'sourceCurrency'   => 'required|alpha_num',                
                'targetCurrency'   => 'required|alpha_num',   
                'type'             => 'sometimes|integer|max:4|min:1',
                'rateType'         => 'required|integer|max:5|min:1',
                'offsetType'       => 'required|integer|max:2|min:1',             
                'syncType'         => 'required|integer|max:1|min:0',      
                'offsetValue'      => 'required|integer',
                'offsetPercentage' => 'required|integer|max:100000|min:0',             
                'rate'             => 'required|integer|min:0',     
                'typeList'         => 'sometimes|array|',     
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['uid']      =  $ext['uid'];         
        $param['createBy']      =  $ext['createBy']; 
        return $this->RateCustomizedService->add($param);
    }

    /**
     * 删除
     * @PostMapping(path = "del")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function del(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->RateCustomizedService->del($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page'                  => 'required|integer|min:1',
                'limit'                 => 'required|integer|min:1',
                'search.status'         => 'sometimes|required|integer|max:1|min:0',
                'search.sourceCurrency' => 'sometimes|required|alpha_num',                
                'search.targetCurrency' => 'sometimes|required|alpha_num',   
                'search.type'           => 'sometimes|required|integer|max:4|min:1',
                'search.rateType'       => 'sometimes|required|integer|max:5|min:1',
                'search.offsetType'     => 'sometimes|required|integer|max:2|min:1',             
                'search.syncType'       => 'sometimes|required|integer|max:1|min:0',             
                'search.rateGroupId'    => 'sometimes|required|uuid',             
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        
        $param = $request->all();
        if(isset($param['search'])){
            $search = $param['search'];

            CustomUtils::xzxAddSearch($param, $search, 'sourceCurrency');
            CustomUtils::xzxAddSearch($param, $search, 'targetCurrency');
            CustomUtils::xzxAddSearch($param, $search, 'rateGroupId');
            CustomUtils::xzxAddSearch($param, $search, 'type');
            CustomUtils::xzxAddSearch($param, $search, 'rateType');
            CustomUtils::xzxAddSearch($param, $search, 'offsetType');
            CustomUtils::xzxAddSearch($param, $search, 'status');
            CustomUtils::xzxAddSearch($param, $search, 'syncType');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }
        

        
        return $this->RateCustomizedService->list($param);
    }

    /**
     *
     * 中行汇率类型下拉框
     * 
     * @PostMapping(path = "getRateTypeOptions")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getRateTypeOptions (RequestInterface $request) {
        return $this->RateCustomizedService->getRateTypeOptions();
    }

    /**
     *
     * 类型下拉框
     * 
     * @PostMapping(path = "getTypeOptions")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getTypeOptions (RequestInterface $request) {
        return $this->RateCustomizedService->getTypeOptions();
    }

    /**
     *
     * 偏移类型下拉框
     * 
     * @PostMapping(path = "getOffsetTypeOptions")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getOffsetTypeOptions (RequestInterface $request) {
        return $this->RateCustomizedService->getOffsetTypeOptions();
    }
   
    /**
     *
     * 同步类型下拉框
     * 
     * @PostMapping(path = "getSyncTypeOptions")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getSyncTypeOptions (RequestInterface $request) {
        return $this->RateCustomizedService->getSyncTypeOptions();
    }

    /**
     * 查询汇率
     * @PostMapping(path = "getTransRateAndAmount")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function getTransRateAndAmount(RequestInterface $request) {
        
        // $param = array();
        // $param['srcCurrency'] = trim($request->post('srcCurrency'));
        // $param['destCurrency'] = trim($request->post('destCurrency'));
        // $param['type'] = trim($request->post('type',5));

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'sourceCurrency' => 'required|alpha',
                'targetCurrency' => 'required|alpha',
                'amount' => 'required',
                'type' => 'required',
                'mchId' => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        $param = $request->all();
        CustomUtils::xzxDebug($param);
        
        return $this->RateCustomizedService->getTransRateAndAmount($param);        
    }
}